<template>
  <!--  <common-dialog-->
  <!--    :title="dialogTitle"-->
  <!--    :visible.sync="dialogShow"-->
  <!--    @open="dialogChange"-->
  <!--    @close="close"-->
  <!--  >-->
  <common-page title="修改手机号">
    <el-button slot="header" @click="back">返 回</el-button>
    <div class="user-phone-edit-wrap" slot="content" v-if="showPhoneDialog">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="验证身份"></el-step>
        <el-step title="绑定新手机"></el-step>
        <el-step title="修改成功"></el-step>
      </el-steps>
      <div class="box" v-if="active === 0">
        <div class="info">原手机号{{ user.encodePhone }}</div>
        <div class="get-box">
          <div class="input-box">
            <el-form ref="form" :model="form" :rules="rules">
              <el-form-item prop="yzm1">
                <common-input
                  v-model="form.yzm1"
                  placeholder="请输入验证码"
                ></common-input>
                <div class="btn">
                  <div
                    class="item"
                    v-if="!phoneYzm"
                    :class="{ disabled: phoneYzm }"
                    @click="sendVerCodeForOldPhoneFun"
                  >
                    获取短信验证码
                  </div>
                  <div class="item" v-else :class="{ disabled: phoneYzm }">
                    验证码已发送({{ phoneYzmTimes }}s)
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div class="notice">短信验证码{{ setValid }}分钟内有效！</div>
        </div>
        <el-button type="primary" @click="next('old')" :loading="nextLoading"
          >下一步</el-button
        >
      </div>
      <div class="box" v-if="active === 1">
        <div class="get-box">
          <el-form ref="emailForm" :model="form" :rules="emailRule">
            <el-form-item prop="phone">
              <common-input
                v-model="form.phone"
                :verify="false"
                placeholder="请输入新手机号"
              ></common-input>
            </el-form-item>
          </el-form>
          <el-form ref="newForm" :model="form" :rules="rule">
            <el-form-item prop="yzm2">
              <common-input
                v-model="form.yzm2"
                placeholder="请输入验证码"
              ></common-input>
              <div class="btn">
                <div
                  class="item"
                  v-if="!phoneYzm"
                  :class="{ disabled: phoneYzm }"
                  @click="sendVerCodeForNewPhoneFun"
                >
                  获取短信验证码
                </div>
                <div class="item" v-else :class="{ disabled: phoneYzm }">
                  验证码已发送({{ phoneYzmTimes }}s)
                </div>
              </div>
            </el-form-item>
          </el-form>
          <div class="notice">短信验证码{{ setValid }}分钟内有效！</div>
        </div>
        <el-button type="primary" @click="next('new')">下一步</el-button>
      </div>
      <div class="box box-success" v-if="active === 2">
        <div class="success-icon">
          <i class="el-icon-success"></i>
        </div>
        <div class="success">新手机号绑定成功！</div>
      </div>
    </div>
  </common-page>
  <!--  </common-dialog>-->
</template>

<script type="text/javascript">
var timeFlag = null;
import {
  sendVerCodeForOldPhone,
  sendVerCodeForNewPhone,
  updateSelfPhone,
  checkUpdateUserInfo,
  getMsgCodeValidTime,
  checkVerCodeForOldPhone,
  checkVerCodeForNewPhone,
} from "@/api/person/index";
import CommonDialog from "@/components/CommonDialog";
import Cookies from "js-cookie";
import { decode, encode } from "@/utils/aesUtils";
import { phoneNumberRule } from "@/utils/formRules";

export default {
  props: {
    showPhoneDialog: {
      type: Boolean,
      default: false,
    },
    // user: {
    //   type: Object,
    //   default: () => {}
    // }
  },
  //存放数据
  data() {
    return {
      dialogTitle: "修改手机号", // 标题
      dialogShow: false, // 是否显示
      user: {
        encodePhone: "",
      },
      form: {
        yzm1: "", //旧手机验证码
        phone: "", //新手机
        yzm2: "", //新手机验证码
        msgVerCodeId: "",
      },
      rules: {
        yzm1: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      emailRule: {
        phone: phoneNumberRule,
      },
      rule: {
        yzm2: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      active: 0,
      phoneYzm: false, //旧手机验证码发送没
      phoneYzmTimes: 60,
      timeFlag: null,
      setValid: 10, //验证码有效期(分钟)
      nextLoading: false,
      isOldCode: false,
      isNewCode: false,
    };
  },
  components: {
    CommonDialog,
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * 获取验证码有效期
     */
    getMsgCodeValidTime() {
      getMsgCodeValidTime().then((res) => {
        if (res && res.code === 200) {
          this.setValid = parseInt(res.msg);
        } else {
          this.setValid = 10;
        }
      });
    },
    /**
     * 关闭
     */
    close() {
      this.dialogShow = false;
      this.form.yzm1 = "";
      this.form.phone = "";
      this.form.yzm2 = "";
      this.form.msgVerCodeId = "";
    },
    /**
     * 显示
     */
    show(form) {
      this.nextLoading = false;
      if (timeFlag) clearInterval(timeFlag);
      this.getMsgCodeValidTime();
      this.dialogShow = true;
      this.user.phonenumber = form.phonenumber;
      this.user.userName = form.userName;
      this.user.userId = form.userId;
      this.user.encodePhone = form.encodePhone;
      const msgVerCodeId = Cookies.get("msgVerCodeId");
      this.form.msgVerCodeId = msgVerCodeId === undefined ? "" : msgVerCodeId;
      this.active = 0;
      this.phoneYzm = false;
      this.phoneYzmTimes = 60;
    },
    /**
     * 验证
     */
    validateForm(formName) {
      return new Promise((resolve, reject) => {
        if (this.$refs[formName]) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              resolve();
            } else {
              reject();
              return false;
            }
          });
        }
      });
    },
    /**
     * 下一步
     */
    next(type) {
      if (type === "old") {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.nextLoading = true;
            checkVerCodeForOldPhone({
              // po: {
              redisKey: "redis_check_old_phone_vercode_",
              userName: this.user.userName,
              msgVerCodeId: this.form.msgVerCodeId,
              msgVerCode: this.form.yzm1,
              phone: this.user.phonenumber,
              // createTime: this.form.createTime,
              businessName: "updatePhone_sendTo_oldPhone",
              // },
            })
              .then((res) => {
                if (res && res.code === 200) {
                  this.form.yzm1 = "";
                  this.phoneYzm = false;
                  this.phoneYzmTimes = 60;
                  // this.form.msgVerCodeId = ''
                  clearInterval(timeFlag);
                  if (this.active++ > 2) this.active = 0;
                } else {
                  this.$GlobalErrorConfirm("操作失败", res.msg).then();
                }
              })
              .finally(() => (this.nextLoading = false));
          }
        });
      }
      if (type === "new") {
        Promise.all([
          this.validateForm("newForm"),
          this.validateForm("emailForm"),
        ]).then(() => {
          this.nextLoading = true;
          checkVerCodeForNewPhone({
            // po: {
            redisKey: "redis_check_new_phone_vercode_",
            userName: this.user.userName,
            msgVerCodeId: this.form.msgVerCodeId,
            msgVerCode: this.form.yzm2,
            phone: encode(this.form.phone),
            // createTime: this.form.createTime,
            businessName: "updatePhone_sendTo_newPhone",
            // },
          })
            .then((res) => {
              if (res && res.code === 200) {
                updateSelfPhone({
                  userId: this.user.userId,
                  phonenumber: encode(this.form.phone),
                }).then((response) => {
                  if (res && res.code === 200) {
                    this.phoneYzm = false;
                    this.phoneYzmTimes = 60;
                    // this.form.msgVerCodeId = ''
                    this.form.yzm2 = "";
                    this.form.phone = "";
                    clearInterval(timeFlag);
                    if (this.active++ > 2) this.active = 0;
                    this.$GlobalSuccessMessage("操作成功");
                    //调用个人信息接口获取最新数据
                    this.$emit("refresh");
                  } else {
                    this.$GlobalErrorConfirm("操作失败", res.msg).then();
                  }
                });
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.nextLoading = false));
        });
      }
    },
    /**
     * 验证旧手机号
     */
    sendVerCodeForOldPhoneFun() {
      if (!this.isOldCode) {
        this.isOldCode = true;
        sendVerCodeForOldPhone({ userName: this.user.userName })
          .then((res) => {
            if (res && res.code === 200) {
              this.phoneYzm = true;
              this.form.msgVerCodeId = res.data.msgVerCodeId;
              let expiresTime = new Date().getTime();
              Cookies.set("msgVerCodeId", res.data.msgVerCodeId, {
                expires: new Date(
                  expiresTime + 60 * 1000 * parseInt(this.setValid)
                ),
              });
              // this.form.createTime = this.utils.getNowTime();
              timeFlag = setInterval(() => {
                this.phoneYzmTimes--;
                if (this.phoneYzmTimes === 0) {
                  this.phoneYzm = false;
                  this.phoneYzmTimes = 60;
                  // this.form.msgVerCodeId = ''
                  clearInterval(timeFlag);
                }
              }, 1000);
            } else {
              this.$GlobalErrorConfirm("获取失败", res.msg).then();
            }
          })
          .finally(() => (this.isOldCode = false));
      }
    },
    /**
     * 验证新手机号
     */
    sendVerCodeForNewPhoneFun() {
      this.$refs["emailForm"].validate((valid) => {
        if (valid) {
          if (!this.isNewCode) {
            this.isNewCode = true;
            checkUpdateUserInfo({
              phonenumber: encode(this.form.phone),
            })
              .then((res) => {
                if (res && res.code === 200) {
                  sendVerCodeForNewPhone({
                    userName: this.user.userName,
                    phone: encode(this.form.phone),
                  }).then((res) => {
                    if (res && res.code === 200) {
                      this.phoneYzm = true;
                      this.form.msgVerCodeId = res.data.msgVerCodeId;
                      // this.form.createTime = this.utils.getNowTime();
                      timeFlag = setInterval(() => {
                        this.phoneYzmTimes--;
                        if (this.phoneYzmTimes === 0) {
                          this.phoneYzm = false;
                          this.phoneYzmTimes = 60;
                          // this.form.msgVerCodeId = ''
                          clearInterval(timeFlag);
                        }
                      }, 1000);
                    } else {
                      this.$GlobalErrorConfirm("获取失败", res.msg).then();
                    }
                  });
                } else {
                  this.$GlobalErrorConfirm("获取失败", res.msg).then();
                }
              })
              .finally(() => (this.isNewCode = false));
          }
        }
      });
      // if (this.form.phone == '') {
      //   this.$message.error('请输入手机号')
      //   return false
      // }
      // if (!/^1[3456789]\d{9}$/.test(this.form.phone)) {
      //   this.$message.error('手机号码不合法，请重新输入')
      //   return false
      // }
      // if (this.form.phone == this.user.phonenumber) {
      //   this.$message.error('不能重复绑定手机号，请换一个新的手机号')
      //   return false
      // }
    },
    clearInterval() {
      if (timeFlag) {
        clearInterval(timeFlag);
        timeFlag = null;
        this.phoneYzmTimes = 60;
      }
    },
    dialogChange() {
      this.clearInterval();
    },
    back() {
      this.$emit("changeDiv");
    },
  },
  destroyed() {
    this.clearInterval();
  },
};
</script>

<style lang="scss" scoped>
.user-phone-edit-wrap {
  padding: 20px;
  box-sizing: border-box;
  margin-top: 50px;

  .box {
    width: 400px;
    margin: 60px auto;
    height: 200px;

    .info {
      padding: 20px 0 0;
      font-size: 15px;
    }

    .get-box {
      padding-bottom: 40px;

      .input-box {
        display: flex;
        align-items: center;
        margin-top: 20px;
      }

      .disabled {
        background-color: #ddd;
        border-color: #ddd;
        color: var(--theme-color) !important;
        cursor: not-allowed;
      }

      .notice {
        font-size: 13px;
        color: #999;
        padding-top: 8px;
      }

      .btn {
        width: 210px !important;
        text-align: center;
        background: var(--theme-color) !important;
        color: #fff;
        height: 32px;
        line-height: 32px;
        cursor: pointer;
      }
    }

    .el-button {
      width: 100%;
    }

    .success-icon {
      width: 100%;
      display: flex;
      justify-content: center;

      .el-icon-success {
        font-size: 60px;
        color: #67c23a;
      }
    }

    .success {
      margin-top: 20px;
      text-align: center;
      font-size: 15px;
    }
  }

  .box-success {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}

::v-deep .el-form {
  .el-form-item__content {
    display: flex;
    align-items: center;
  }
}
</style>
